/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.globussoft.xml;

import java.io.*;
import java.util.HashMap;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class CreatXMLFile {
  private String  projectName ="Pomblast";
    public static void main(String[] args) throws Exception {
        HashMap hash = new HashMap();
        hash.put("sunil", "true");
        hash.put("kumar", "true");
        CreatXMLFile xmlfile = new CreatXMLFile();//.writeXmlFile(hash);
        CreatXMLFile.writeXmlFile(System.getProperty("user.home") + "/"+xmlfile.projectName+"/FilesToUpload.xml", hash);
        xmlfile.changeXmlStatusNode(System.getProperty("user.home") + "/"+xmlfile.projectName+"/FilesToUpload.xml", "kumar", false);

    }

    public CreatXMLFile() {
        projectName=SettingsXml.getProjectName();
    }


    public static void writeXmlFile(String path, HashMap FileList) {
        try {
            try {
                File fileObj1 = new File(path.substring(0, path.lastIndexOf("/")));
                if (fileObj1.exists() == false) {
                    fileObj1.mkdir();
                }
                
//                File fileObj2 = new File(path);
//                if(fileObj2.exists())
//                {
//                    HashMap temp = new HashMap();
//                    temp=ReadXmlFile(path);
//                    Object [] objArr= temp.keySet().toArray();
//                    if(objArr!=null)
//                    {
//                        int len = objArr.length;
//                         for(int i=0;i<len;i++)
//                         FileList.put(objArr[i].toString(),temp.get(objArr[i].toString()));
//                    }
//                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            Element rootElement = document.createElement("property");
            document.appendChild(rootElement);
            int HashLength = FileList.size();
            Object[] Files = FileList.keySet().toArray();
            for (int i = 0; i < HashLength; i++) {
                Element data = document.createElement("data");
                Element filepath = document.createElement("file-path");
                filepath.appendChild(document.createTextNode(Files[i].toString()));
                Element filestatus = document.createElement("file-status");
                String nodeStatus = FileList.get(Files[i].toString()).toString();
                if (nodeStatus.equals("false")) {
                    filestatus.appendChild(document.createTextNode("UnStored"));
                } else {
                    filestatus.appendChild(document.createTextNode("Stored"));
                }
                data.appendChild(filepath);
                data.appendChild(filestatus);
                rootElement.appendChild(data);
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            FileOutputStream fout = new FileOutputStream(path);
            StreamResult result = new StreamResult(fout);
            transformer.transform(source, result);
            fout.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void changeXmlStatusNode(final String path, final String nodeName, final boolean value) {
//        new Thread() {
//            @Override
//            public void run() {
                HashMap tempHash = ReadXmlFile(path,false);
                tempHash.remove(nodeName);
                tempHash.put(nodeName, value);
                writeXmlFile(path, tempHash);
//            }
//        }.start();

    }

    public static HashMap ReadXmlFile(String path,boolean onlyTrue) {
        HashMap map = new HashMap();
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(path.trim().replace("\\","/")));

            // normalize text representation
            doc.getDocumentElement().normalize();
            NodeList listOfPersons = doc.getElementsByTagName("data");
            int totalPersons = listOfPersons.getLength();
            for (int s = 0; s < listOfPersons.getLength(); s++) {


                Node firstPersonNode = listOfPersons.item(s);
                if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) firstPersonNode;
                    //-------
                    NodeList firstNameList = firstPersonElement.getElementsByTagName("file-path");
                    Element firstNameElement = (Element) firstNameList.item(0);
                    NodeList textFNList = firstNameElement.getChildNodes();
                    //   System.out.println("First Name : " +
                    //     ((Node)textFNList.item(0)).getNodeValue().trim());
                    //-------
                    NodeList lastNameList = firstPersonElement.getElementsByTagName("file-status");
                    Element lastNameElement = (Element) lastNameList.item(0);
                    NodeList textLNList = lastNameElement.getChildNodes();
                    if(!onlyTrue)
                    map.put(((Node) textFNList.item(0)).getNodeValue().trim(), ((Node) textLNList.item(0)).getNodeValue().trim().equals("Stored") ? "true" : "false");
                    else{
                       if(((Node) textLNList.item(0)).getNodeValue().trim().equals("UnStored"))
                       map.put(((Node) textFNList.item(0)).getNodeValue().trim(), "false");
                    }

                }//end of if clause


            }//end of for loop with s var


        } catch (SAXParseException err) {
            System.out.println("** Parsing error" + ", line "
                    + err.getLineNumber() + ", uri " + err.getSystemId());
            System.out.println(" " + err.getMessage());

        } catch (SAXException e) {
            Exception x = e.getException();
            ((x == null) ? e : x).printStackTrace();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;
    }
}
